<template>
  <div class="menus-add-root">
    <el-card>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="菜单显示名称" prop="menuName">
          <el-input v-model="form.menuName" />
        </el-form-item>

        <el-form-item label="父菜单ID" prop="parentID">
          <el-input v-model="form.parentID" placeholder="例如：0 表示顶级" />
        </el-form-item>

        <el-form-item label="访问路径" prop="url">
          <el-input v-model="form.url" placeholder="例如：/system/role" />
        </el-form-item>

        <el-form-item label="排序序号" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" />
        </el-form-item>

        <el-form-item>
          <el-button :loading="isSubmitting" type="primary" @click="submit">保存</el-button>
          <el-button :disabled="isSubmitting" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { read, menuApi } from '@/assets/Axios/axiosH'

const formRef = ref()
const form = reactive({ menuName: '', parentID: '0' as string | number | null, url: '', sortOrder: 0 })
const isSubmitting = ref(false)
const rules = {
  menuName: [{ required: true, message: '请输入菜单显示名称', trigger: 'blur' }],
  url: [{ required: true, message: '请输入访问路径', trigger: 'blur' }]
}

const parentOptions = ref<Array<any>>([])

async function loadParents() {
  try {
    const res = await read.get('/api/SystemManagement/MenusShow')
    const payload = res.data && (res.data.data ?? res.data)
    const items = Array.isArray(payload) ? payload : (payload?.data ?? [])
    parentOptions.value = [({ id: 0, menuName: '顶级 (0)' })].concat((items || []).map((it: any) => ({ id: it.id ?? it.Menuid, menuName: it.MenuName ?? it.menuName ?? it.name })))
  } catch (e) {
    console.error('loadParents error', e)
  }
}

async function submit() {
  try {
    // 使用可选链以防 formRef 尚未挂载导致调用失败
    await formRef.value?.validate?.()
  } catch (err) { return }
  isSubmitting.value = true
  try {
    const payload = { MenuName: form.menuName, ParentID: Number(form.parentID) || 0, Url: form.url, SortOrder: form.sortOrder }
    await menuApi.addMenu(payload)
    reset()
  } catch (e: any) {
    // 错误处理已在 menuApi.addMenu 中完成，这里不需要额外处理
    console.error('菜单添加失败:', e)
  } finally {
    isSubmitting.value = false
  }
}

function reset() {
  form.menuName = ''
  form.parentID = '0'
  form.url = ''
  form.sortOrder = 0
  formRef.value?.resetFields?.()
}

onMounted(() => { loadParents() })
</script>

<style scoped>
.menus-add-root {
  padding: 0;
  height: 100%;
  box-sizing: border-box;
}

.menus-add-root .el-card {
  height: 100%;
  box-shadow: none;
}

.menus-add-root .el-form {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
</style>